package servlet;

import bean.AdInfo;
import com.alibaba.fastjson.JSON;
import service.AdInfoService;
import service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet({"/getAlladInfo"})
public class ManagerAdInfoServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");// 设置请求参数的编码格式
        response.setContentType("text/html;charset=utf-8");// 设置网页界面相应的代码
        response.setHeader("Access-Control-Allow-Origin", "*");// 允许所有来源访问
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");// 允许指定的请求方法访问
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");// 允许自定义的请求头部

        String requestURI = request.getRequestURI();
        AdInfoService service = new AdInfoService();
        UserService userService = new UserService();
        if (requestURI.endsWith("/getAlladInfo")) {//获取所有广告信息
            List<AdInfo> allInfo = service.getAllInfo();
            System.out.println(allInfo);
            // 遍历列表集合，逐个更新 user_id 字段
            for (AdInfo adInfo : allInfo) {
                String id = adInfo.getUser_id();
                // 根据id获取用户名
                String username = userService.getUsername(id);
                // 将获取到的用户名设置为 user_id 字段
                adInfo.setUser_id(username);
            }
            String allInfojson = JSON.toJSONString(allInfo);
            response.getWriter().write(allInfojson);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
